import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * Created by lanouhn on 17/7/18.
 */
public class JavaPictureRequest {

    public static void main(String[] args) {


        try {
            String myUrl = "http://pic96.nipic.com/file/20160429/21289054_220047597697_2.jpg";
            URL url = null;
            url = new URL(myUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while( (len=inStream.read(buffer)) != -1 ){
                outStream.write(buffer, 0, len);
            }
            inStream.close();
            byte[] btImg = outStream.toByteArray();

            if(null != btImg && btImg.length > 0){
                System.out.println("读取到：" + btImg.length + " 字节");

                //存储请求结果（存在桌面txt）
                String path = "/Users/lanouhn/Desktop/java/picture.jpg";
                File file = new File(path);

                FileOutputStream fops = new FileOutputStream(file);
                fops.write(btImg);
                fops.flush();
                fops.close();
                System.out.println("图片已经下载");

            }else{
                System.out.println("没有从该连接获得内容");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}